<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      title="导入表"
      :helpMessage="['导入要生成的表']"
      width="1000px"
      cancelText="取消"
      okText="导入"
      @ok="doImport"
      @register="register"
      :destroyOnClose="true"
    >
      <BasicTable @register="registerTable" />
    </BasicModal>
  </div>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, BasicColumn, FormSchema } from '@/components/Table';

  import { candidateTables, importTables } from '@/api/toolkit/tableConfig';

  import { BasicModal, useModalInner } from '@/components/Modal';

  import { formatToDateTime } from '@/utils/dateUtil';

  const [register, { closeModal, setModalProps }] = useModalInner();

  // 搜索面板
  const searchFormSchema: FormSchema[] = [
    {
      field: 'tableName',
      label: '表名',
      component: 'Input',
      colProps: { span: 9 },
    },
    {
      field: 'tableComment',
      label: '注释',
      component: 'Input',
      colProps: { span: 9 },
    },
  ];

  // 表格列
  const columns: BasicColumn[] = [
    {
      title: '表名',
      dataIndex: 'tableName',
      width: 120,
      align: 'left',
    },
    {
      title: '数据库名',
      dataIndex: 'tableSchema',
      width: 150,
      align: 'left',
    },
    {
      title: '注释',
      dataIndex: 'tableComment',
      width: 150,
      align: 'left',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 150,
      align: 'left',
      format: (text) => formatToDateTime(text),
    },
  ];

  // 表格
  const [registerTable, { reload, getSelectRowKeys }] = useTable({
    title: '',
    api: candidateTables,
    columns,
    // 搜索框配置: 是否打开搜索框、搜索框配置
    useSearchForm: true,
    formConfig: {
      labelWidth: 90,
      schemas: searchFormSchema,
      labelAlign: 'right',
      autoSubmitOnEnter: true,
      showResetButton: false,
      submitOnChange: true,
    },
    // 表格配置:
    showTableSetting: false, // 是否显示设置按钮
    bordered: true, // 是否包含边框
    showIndexColumn: false, // 是否包含索引列
    defSort: {
      // 排序字段
      field: 'createTime',
      order: 'asc',
    },
    rowKey: 'tableName', // 选择时值
    rowSelection: {
      type: 'checkbox',
    },
  });

  async function doImport() {
    let items: any[] = getSelectRowKeys();

    // 导入表
    await importTables(items);

    // 重新加载
    reload();

    // 关闭对话框
    closeModal();
  }
</script>
